from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from rest_framework_jwt.settings import api_settings
from rest_framework.response import Response
from django.utils import timezone
from rest_framework import status
from rest_framework import serializers
from django.contrib.auth import authenticate, get_user_model
from utitls.send_sms_email import my_send_mail
from .serializers import UserLoginSerializer, UserRegisterCaptchaCreateSerializer, UserLoginV2Serializer
from .tasks import reg_send_mail
from .serializers import CaptchaReg

from drf_movie_rimi.settings import EMAIL_CAPTCHA


class UserLogin(APIView):
    # 如果是post请求
    def post(self, request):
        # 我们验证他的post数据,和序列化
        datas = UserLoginSerializer(data=request.POST)
        if datas.is_valid():
            # 我们把验证成功的数据交给django验证
            user = authenticate(**datas.validated_data)
            if user:
                # 调用jwt官方指定的方法加密用户信息获取到token
                jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                return Response({'token': token})
        # 如果失败,我们统一返回401表示登录不成功
        return Response(status=401)


class UserRegister(APIView):
    # 如果是post请求
    def post(self, request):
        # 我们验证他的post数据,和序列化
        datas = UserLoginV2Serializer(data=request.POST)
        if datas.is_valid():
            # 我们把验证成功的数据交给django验证
            data = datas.validated_data
            # 获取用户model
            User = get_user_model()
            # 获取用户信息
            user = User.objects.filter(username=data['username'])
            # 如果有用户则不创建用户
            if not user:
                user = User.objects.create_user(**data)
                # 调用jwt官方指定的方法加密用户信息获取到token
                jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                return Response({'token': token})
        # 如果失败,我们统一返回401表示登录不成功
        return Response(status=401)


class UserRegisterV2(APIView):
    # 如果是post请求
    def post(self, request):
        # 我们验证他的post数据,和序列化
        datas = UserLoginV2Serializer(data=request.POST)
        if datas.is_valid():
            # 我们把验证成功的数据交给django验证
            data = datas.validated_data
            # 获取用户model
            User = get_user_model()
            # 获取用户信息
            user = User.objects.filter(username=data['username'])
            # 如果有用户则不创建用户
            if user:
                raise serializers.ValidationError('用户名重复')

            # 验证验证码码是否正确
            expire_time = timezone.now() - timezone.timedelta(minutes=EMAIL_CAPTCHA['expire_time']['register'])

            if not CaptchaReg.objects.filter(email=data['email'], captcha=data['captcha'],
                                             add_time__gt=expire_time).exists():
                raise serializers.ValidationError('邮箱错误或验证码失效')

            user = User.objects.create_user(**data)
            # 调用jwt官方指定的方法加密用户信息获取到token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return Response({'token': token})
        # 如果失败,我们统一返回401表示登录不成功
        return Response(status=401)

##################################
# 通过mixin来创建用户
from django.contrib.auth.hashers import make_password
from django.contrib.auth import get_user_model
from rest_framework import mixins

User = get_user_model()


class UserInfoSerializer(serializers.ModelSerializer):

    # 这个步骤是专门给你用的,用于你去修改已经验证好的数据,大前提是你的数据通过验证了
    # 才去做定制化
    def validate(self, attrs):
        attrs['password'] = make_password(attrs['password'])
        return super().validate(attrs)

    class Meta:
        model = User
        fields = ("username", 'password')


class UserInfoViewSet(mixins.CreateModelMixin, GenericViewSet):
    serializer_class = UserInfoSerializer
    queryset = User.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({'token': token}, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()

##################################

class UserRegisterCaptchaCreateViewSet(CreateModelMixin, GenericViewSet):
    queryset = UserRegisterCaptchaCreateSerializer.Meta.model.objects.all()
    serializer_class = UserRegisterCaptchaCreateSerializer

    def perform_create(self, serializer):
        """
        boker
        :param serializer:
        :return:
        """
        data = serializer.validated_data
        captcha = '您的验证码为{}'.format(data['captcha'])
        # res = my_send_mail('注册验证码',captcha,data['email'])
        # if not res:
        #     return Response(status=401)

        reg_send_mail.delay('注册验证码', captcha, data['email'])
        return super().perform_create(serializer)

#